<template>
    <div class="session-container">
        <van-loading v-if="loadingStatus" size="48px" vertical>
            呼叫中...
        </van-loading>
        <SessionProgress
            v-if="showSessionProgress"
            :waitingNumber="waitingNumber"
            :currentPosition="currentPosition"
            :ticket="ticket"
            :progressTitle="progressTitle"
        />
        <SystemError :show="showSystemError" @close="onCloseSystemError" />
        <SubmitForm v-if="showSubmitForm" :ticket="ticket" @close="onSubmit" />
        <guide v-show="showGuide" @closeGuide="closeGuide" />
    </div>
</template>

<script>
import Vue from "vue";
import { Loading, Toast, Notify } from "vant";
Vue.use(Loading);
Vue.use(Toast);
Vue.use(Notify);
import { mapActions, mapState } from "vuex";
import SessionProgress from "./SessionProgress.vue";
import SystemError from "../error/SystemError.vue";
import { return2Main } from "../../lib/util";
import {
    updateSessionId,
    createTicket,
    getAvailableAgent,
} from "../../api/api";
import SubmitForm from "../error/SubmitForm.vue";
import Guide from "../device/Guide.vue";

export default {
    components: { SessionProgress, SystemError, SubmitForm, Guide },
    data() {
        return {
            showSessionProgress: true,
            waitingNumber: 0,
            currentPosition: 1,

            mode: "video", //呼叫的模式，默认是视频呼叫
            loadingStatus: true, //是否显示loading
            showSystemError: false,
            sessionId: "",

            phone: "",
            phoneMask: "",
            showSubmitForm: false,

            openId: "",
            mid: "",
            ZFWZL_CODE: "",

            ticket: {},
            mediaStatus: "", /// ‘audio’ || 'video'
            progressTitle: "", // 呼叫等待页面文案
            showGuide: false,
        };
    },
    computed: {
        ...mapState("app", ["ticketId"]),
        // ...mapState("user", ["openid", "mid", "modeType"]),
    },
    watch: {
        sessionId(newVal) {
            if (newVal && this.ticketId) {
                this.updateSessionId(newVal);
            }
        },
        ticketId(newVal) {
            if (newVal && this.sessionId) {
                this.updateSessionId(this.sessionId);
            }
        },
    },
    mounted() {
        this.setTicketId("");
        const param = localStorage.getItem("mindray-cunstomer-call-param");
        const params = JSON.parse(param);
        this.ZFWZL_CODE = params.ZFWZL_CODE;
        this.mid = params.mid;
        this.openId = params.openId;

        this.phone =
            this.$route.query.phone || localStorage.getItem("phoneNumber");
        this.phoneMask = this.phone.replace(
            /\b(\w{3})\w+(\w{4})\b/g,
            "$1****$2"
        );
        this.createTicket();
        const bizscenarioId = this.$route.query.id || "";
        const headerSceneId = this.$route.query.headerId || "";

        this.getAvailableAgent(bizscenarioId, headerSceneId);

        document.addEventListener("visibilitychange", () => {
            if (document.visibilityState === "visible") {
                // if (this.mediaStatus === "video") {
                //     ivcsCustomer.upgradeCall(
                //         () => {},
                //         (error) => {
                //             console.error("upgrade call ", error);
                //         }
                //     );
                // }
                // // 设置订阅的是否 恢复订阅
                // ivcsCustomer.setSubscriptionMute(false, "video");
                // // 访客端 回到前台后重新render订阅的坐席画面
                // ivcsCustomer.renderAllSubscription();
            } else {
                //
                // this.mediaStatus = ivcsCustomer.getMediaStatus();
                // if (this.mediaStatus === "video") {
                //     ivcsCustomer.downgradeCall(
                //         () => {},
                //         (error) => {
                //             console.error("downgrade call ", error);
                //         }
                //     );
                // }
                // // 设置订阅的是否 停止订阅
                // ivcsCustomer.setSubscriptionMute(true, "video");
            }
        });
    },
    methods: {
        ...mapActions("app", ["updateHangupReason", "setTicketId"]),

        closeGuide() {
            console.log("closeGuide");
            this.showGuide = false;
        },

        /**
         * 呼叫客服
         * @param {string} bizscenarioId  业务场景id
         */
        videochat(bizscenarioId) {
            console.log("videochat ", bizscenarioId);
            if (!bizscenarioId) {
                this.showSystemError = true;
                return;
            }
            this.loadingStatus = true;
            localStorage.setItem("visittype", 3);
            if (bizscenarioId) {
                // 判断ivcsCustomer 是否加载成功
                if (window.ivcsCustomer) {
                    this.initCall(bizscenarioId);
                } else {
                    let interval = setInterval(() => {
                        if (window.ivcsCustomer) {
                            clearInterval(interval);
                            interval = null;
                            this.initCall(bizscenarioId);
                        }
                    }, 200);
                }
            }
        },

        /**
         * 呼叫判断
         */
        initCall(bizscenarioId) {
            this.initWidget();
            if (this.mode === "audio") {
                sessionStorage.setItem("callMediaType", "audio");
                sessionStorage.setItem("receiveMediaType", "audio");
                // this.requestSession(bizscenarioId, "audio");
            } else if (this.mode === "video") {
                sessionStorage.setItem("callMediaType", "video");
                sessionStorage.setItem("receiveMediaType", "video");
                let mediaType = "video";
                console.log("call media type", mediaType);
                this.requestSession(bizscenarioId, mediaType);
            }
        },

        // 初始化组件
        initWidget() {
            let option = {
                debug: true,
                backendUrl: loginUrl,
                org: mindrayOrg, // "mindray",
                visitorId: this.phoneMask,
                account: {
                    name: "", // zw,
                    password: "", // 123456,
                    visitorId: this.phoneMask,
                },
                bizName: "卡证收集", // sessionStorage.getItem("bizScenarioName"),
                orgName: "迈瑞医疗",
                formUrl: formUrl,
                // parentNodeId: "ivcs-widget-container",
                resourceOriginUrlDomain: "ivcs-nginx",
                resourceReplaceUrlDomain: "vservice.mindray.com",
                hidePhotoButton: true,
                pdfViewerUrl:
                    "https://vservice.mindray.com/client/static/pdf/web/viewer.html",
                countlyAppKey: "0d3e568265713f3499f606b92a776854f375a6e2",
                countlyHost: "https://countly.cosee.cc",
                hideMineName: true,
                defaultMediaOptions: defaultMediaOptions,
            };
            if (
                localStorage.getItem("debug") &&
                localStorage.getItem("debug") == 0
            ) {
                option.debug = false;
            }
            console.log("init ", option);
            ivcsCustomer.getInstance(option);
            let toolOptions = {
                show_screenSync_stop: true,
                show_screenSync_hangup: true,
                show_layout_change: true,
                show_switch_camera: true,
                show_mute_voice: true,
                show_media_controls: true,
                show_session_hangup: true,
                show_im: true,
                show_inviteOthers: false,
            };

            ivcsCustomer.initToolBar(
                toolOptions.show_screenSync_stop,
                toolOptions.show_screenSync_hangup,
                toolOptions.show_layout_change,
                toolOptions.show_switch_camera,
                toolOptions.show_mute_voice,
                toolOptions.show_media_controls,
                toolOptions.show_session_hangup,
                toolOptions.show_im,
                toolOptions.show_inviteOthers
            );
        },

        onCustomerAutoHangup() {
            ivcsCustomer.onCustomerAutoHangup((info) => {
                console.warn("onCustomerQuitSession", info);
                sessionStorage.setItem("username", "");
                sessionStorage.setItem("idcard", "");
                sessionStorage.setItem("mobile", "");
                sessionStorage.setItem("address", "");
                sessionStorage.setItem("selfimg", "");
                sessionStorage.setItem("idcardFront", "");
                sessionStorage.setItem("idcardBack", "");
                sessionStorage.setItem("bankImg", "");
                sessionStorage.setItem("company", "");
                sessionStorage.setItem("category", "");
                sessionStorage.setItem("gender", "");

                // info ： undefine 通话挂断 cancel 取消呼叫
                if (
                    !info ||
                    [
                        "rated",
                        "system-error",
                        "notfound",
                        "offday",
                        "offtime",
                        "scenariodisabled",
                    ].includes(info)
                ) {
                    return2Main();
                } else {
                    if (this.showSessionProgress) {
                        this.updateHangupReason(info);
                    } else {
                        if (
                            [
                                "cancel",
                                "ringingTimeout",
                                "the specified agent is rejected",
                                "rejected",
                            ].includes(info)
                        ) {
                            this.showSubmitForm = true;
                        }
                    }
                }
            });
        },

        onInviteProgress() {
            ivcsCustomer.listenInviteProgress((data) => {
                const { code, waitingNumber, currentPosition } = data;
                this.waitingNumber = waitingNumber || 0;
                this.currentPosition = currentPosition || 0;
                if (code === "403") {
                    this.progressTitle = "正在为您接通…";
                }
                if (code === "401") {
                    this.progressTitle = "正在连接服务器";
                }
                if (code === "405") {
                    // "坐席已接听";
                    this.showSessionProgress = false;
                    this.progressTitle = "";
                }
                if (waitingNumber && waitingNumber > 0) {
                    this.progressTitle = "";
                    this.currentPosition =
                        this.currentPosition === 0 ? 1 : this.currentPosition;
                }
            });
        },

        onCameraPermissionForbid() {
            ivcsCustomer.onCameraPermissionForbid(() => {
                console.log("onCameraPermissionForbid");
                this.showGuide = true;
            });
        },

        /**
         * 根据业务场景id呼叫坐席
         * @param {string} bizscenarioId  业务场景id
         * @param {string} callType 呼叫类型  enum['im'="文本聊天",'audio'='语音通话','video'='视频通话'] 受callAgentProperty类型影响，im只支持人工坐席
         */
        requestSession(bizscenarioId, callType) {
            let userData = {
                name: localStorage.getItem("name") || "",
                userName: this.phone,
                fullName: sessionStorage.getItem("username") || "", // 提交资料填写的用户名
                isScreenSyncMode: false,
                userId: this.phone || "",
                gender: sessionStorage.getItem("gender") || "",
                formId: this.$store.state.formId,
                idCard: sessionStorage.getItem("idcard") || "",
                phoneNumber: sessionStorage.getItem("phoneNumber"),
                homeAddress: sessionStorage.getItem("address") || "",
                customerRole: "访客",
                businessflowId: "",
                openId: this.openId,
            };

            ivcsCustomer.callScenario(
                bizscenarioId, // 业务场景id
                callType,
                "human",
                userData,
                false, // showInviteProgressView,
                true, // showSessionVideoView
                (res) => {
                    console.log(
                        `'request session success',${JSON.stringify(
                            res
                        )},${new Date()}`
                    );
                    this.onCustomerAutoHangup();
                    this.onInviteProgress();
                    this.onCameraPermissionForbid();
                    this.loadingStatus = false;
                    this.showSessionProgress = true;
                    // update ticket res.sessionId
                    this.sessionId = res.sessionId;
                    // this.updateSessionId(res.sessionId);
                },
                (error) => {
                    console.error(
                        `'request session error',${JSON.stringify(
                            error
                        )},${new Date()}`
                    );

                    this.loadingStatus = false;
                    this.showSystemError = true;
                    // Notify({
                    //     type: "warning",
                    //     message: JSON.stringify(error),
                    //     duration: 10000,
                    // });
                }
            );
        },
        updateSessionId(sessionId) {
            if (!this.ticketId || !sessionId) return;
            updateSessionId(this.ticketId, sessionId)
                .then((resp) => {
                    const { code } = resp.data;
                    if (code === "0000") {
                        console.log("update session id success ", resp);
                    } else {
                        console.warn("update session id error ", resp);
                    }
                })
                .catch((err) => {
                    console.error("update session id error ", err);
                });
        },
        createTicket() {
            // {openId, sn, phone, ZFWZL_CODE, XCX_ID} ZFWZL_CODE: 001=维修|007=临床服务, XCX_ID: sessionId
            const data = {
                openId: this.openId,
                sn: this.mid,
                phone: this.phone,
                ZFWZL_CODE: this.ZFWZL_CODE,
                XCX_ID: new Date().getTime(),
            };
            createTicket(data)
                .then((resp) => {
                    const { code, data } = resp.data;
                    if (code === "0000" && data) {
                        // orderId 	生成的工单号
                        // FLAG 0:成功 其它：失败
                        const curTicketId = data.id || "";
                        this.setTicketId(curTicketId);
                        this.ticket = data;
                        console.warn("createTicket ", this.ticket);
                    } else {
                        console.warn("create ticket error ", resp);
                        // this.showSystemError = true;
                    }
                })
                .catch((err) => {
                    console.error("create ticket error ", err);
                    // this.showSystemError = true;
                });
        },
        onCloseSystemError() {
            this.showSystemError = false;
            return2Main();
        },
        onSubmit() {
            this.showSubmitForm = false;
            return2Main();
        },
        // get available agent
        getAvailableAgent(bizscenarioId, headerSceneId) {
            let hasAgent = false;
            getAvailableAgent(bizscenarioId)
                .then((resp) => {
                    const { code, data } = resp.data;
                    if (code === 200 && data) {
                        console.warn(
                            "getAvailableAgent ",
                            data,
                            bizscenarioId,
                            headerSceneId
                        );
                        if (data.length > 0) {
                            hasAgent = true;
                        }
                    } else {
                        console.warn("get available agent error ", resp);
                    }
                })
                .catch((err) => {
                    console.error("get available agent error ", err);
                })
                .finally(() => {
                    this.videochat(hasAgent ? bizscenarioId : headerSceneId);
                });
        },
    },
};
</script>

<style lang="less" scoped>
.session-container {
    width: 100%;
    height: 100%;
    overflow-y: hidden;

    .van-loading {
        margin-top: 50%;
    }
}
</style>
